import { Alias as A } from '../nodes/Alias.js';
import { composeCollection as g } from './compose-collection.js';
import { composeScalar as p } from './compose-scalar.js';
import { resolveEnd as d } from './resolve-end.js';
import { emptyScalarPosition as b } from './util-empty-scalar-position.js';
const y = { composeNode: h, composeEmptyNode: u };
function h(t, e, n, o) {
  const { spaceBefore: r, comment: a, anchor: s, tag: i } = n;
  let c,
    l = !0;
  switch (e.type) {
    case 'alias':
      (c = S(t, e, o)),
        (s || i) &&
          o(e, 'ALIAS_PROPS', 'An alias node must not specify any properties');
      break;
    case 'scalar':
    case 'single-quoted-scalar':
    case 'double-quoted-scalar':
    case 'block-scalar':
      (c = p(t, e, i, o)), s && (c.anchor = s.source.substring(1));
      break;
    case 'block-map':
    case 'block-seq':
    case 'flow-collection':
      (c = g(y, t, e, i, o)), s && (c.anchor = s.source.substring(1));
      break;
    default: {
      const f =
        e.type === 'error' ? e.message : `Unsupported token (type: ${e.type})`;
      o(e, 'UNEXPECTED_TOKEN', f),
        (c = u(t, e.offset, void 0, null, n, o)),
        (l = !1);
    }
  }
  return (
    s &&
      c.anchor === '' &&
      o(s, 'BAD_ALIAS', 'Anchor cannot be an empty string'),
    r && (c.spaceBefore = !0),
    a &&
      (e.type === 'scalar' && e.source === ''
        ? (c.comment = a)
        : (c.commentBefore = a)),
    t.options.keepSourceTokens && l && (c.srcToken = e),
    c
  );
}
function u(
  t,
  e,
  n,
  o,
  { spaceBefore: r, comment: a, anchor: s, tag: i, end: c },
  l,
) {
  const f = {
      type: 'scalar',
      offset: b(e, n, o),
      indent: -1,
      source: '',
    },
    m = p(t, f, i, l);
  return (
    s &&
      ((m.anchor = s.source.substring(1)),
      m.anchor === '' && l(s, 'BAD_ALIAS', 'Anchor cannot be an empty string')),
    r && (m.spaceBefore = !0),
    a && ((m.comment = a), (m.range[2] = c)),
    m
  );
}
function S({ options: t }, { offset: e, source: n, end: o }, r) {
  const a = new A(n.substring(1));
  a.source === '' && r(e, 'BAD_ALIAS', 'Alias cannot be an empty string'),
    a.source.endsWith(':') &&
      r(e + n.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', !0);
  const s = e + n.length,
    i = d(o, s, t.strict, r);
  return (a.range = [e, s, i.offset]), i.comment && (a.comment = i.comment), a;
}
export { u as composeEmptyNode, h as composeNode };
